package com.example.hfut_edu;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class page_daka extends AppCompatActivity {
    public static page_daka daka_obj = null;
    private HandlerThread handlerThread;
    TextView text_xxmh_xuehao;
    EditText editText_ad;
    Button btn_daka;
    RadioGroup rdg_ad;
    RadioButton rdb_0,rdb_1;
    Switch switch_auto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_page_daka);
        daka_obj =this;


        text_xxmh_xuehao=findViewById(R.id.text_xxmh_xuehao);
        btn_daka=findViewById(R.id.btn_daka);
        rdg_ad=findViewById(R.id.rdg_ad);
        rdb_1=findViewById(R.id.rdb_1);
        rdb_0=findViewById(R.id.rdb_0);
        editText_ad=findViewById(R.id.editText_ad);
        switch_auto=findViewById(R.id.switch_auto);


        if (rwSPdata("r","if_checked","").contains("yes")){
            switch_auto.setChecked(true);
        }


        text_xxmh_xuehao.setText(rwSPdata("r","xxmh_account","请先登陆信息门户"));

        rdb_0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v1) {
                editText_ad.setVisibility(View.GONE);
            }
        });
        rdb_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v1) {
                editText_ad.setVisibility(View.VISIBLE);
                editText_ad.setText(rwSPdata("r","diy_ad",""));
            }
        });


        init();
    }



    private void init(){

        handlerThread = new HandlerThread("loginpage_xxmh");
        handlerThread.start();
        final Handler handler = new Handler(handlerThread.getLooper());

        btn_daka.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v1) {
                timer.start();
                int count = rdg_ad.getChildCount();
                //Toast.makeText(page_daka.this, "选中"+count, Toast.LENGTH_SHORT).show();
                for(int i = 0 ;i < 2;i++){
                    RadioButton rb = (RadioButton)rdg_ad.getChildAt(i);
                    if(rb.isChecked()){
                        String view_id=getResources().getResourceEntryName(rb.getId());
                        String user_ad;
                        //Toast.makeText(page_daka.this, "选中"+view_id, Toast.LENGTH_SHORT).show();
                        if (view_id.toString().contains("rdb_0")){
                            user_ad="安徽省合肥市蜀山区广玉兰路";
                        }else if (view_id.toString().contains("rdb_1")){
                            user_ad=editText_ad.getText().toString();
                        }else {
                            user_ad="安徽省合肥市蜀山区广玉兰路";
                        }

                        if (rwSPdata("r","xxmh_account","").isEmpty()){
                            Intent intent=new Intent(page_daka.this, page_login_xxmh.class);
                            intent.putExtra("extra_data","信息门户登陆");
                            startActivity(intent);
                        }else {
                            //请求打卡

                            String xxmh_account= rwSPdata("r","xxmh_account","");
                            String xxmh_passwd= rwSPdata("r","xxmh_passwd","");

                            String daka_url="daka?xuehao=" + xxmh_account + "&passwd=" + xxmh_passwd+"&ad="+user_ad;
                            handler.post(new page_daka.Runable_Task(daka_url));
                        }
                    }
                }
            }
        });


        switch_auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    //选中状态
                    Toast.makeText(page_daka.this, "正在请求", Toast.LENGTH_LONG).show();
                    rwSPdata("w","if_checked","yes");
                    String xxmh_account= rwSPdata("r","xxmh_account","");
                    String xxmh_passwd= rwSPdata("r","xxmh_passwd","");
                    String daka_auto="signin?xuehao=" + xxmh_account + "&passwd=" + xxmh_passwd+"&email=";
                    handler.post(new page_daka.Runable_Task(daka_auto));
                }else {
                    //未选中状态
                    Toast.makeText(page_daka.this, "正在请求", Toast.LENGTH_LONG).show();
                    rwSPdata("w","if_checked","no");
                    String xxmh_account= rwSPdata("r","xxmh_account","");
                    String daka_auto="del_account?xuehao=" + xxmh_account;
                    handler.post(new page_daka.Runable_Task(daka_auto));
                }
            }
        });
    }

    class Runable_Task implements Runnable {
        String API_URL;
        public Runable_Task(String API_URL) {
            this.API_URL = API_URL;
        }
        @Override
        public void run() {
            //耗时任务开始-----------------
            getdata_HTTP(API_URL);
            //----------------------------耗时任务结束
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerThread.quit();//停止Looper的循环
    }

    public void getdata_HTTP(String get_url) {

        String userdata;
        try {
            HttpURLConnection connection = null;
            try {

                //URL url = new URL("https://iou.ink/file/temp/user.json");
                //URL url = new URL("http://155.94.158.151:23002/HFUTcourse/"+get_url);
                URL url = new URL("https://api.iou.ink/hfut-daka/"+get_url);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");//设置访问方式为“GET”
                connection.setConnectTimeout(15000);//设置连接服务器超时时间为8秒
                connection.setReadTimeout(15000);//设置读取服务器数据超时时间为8秒

                if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                    //从服务器获取响应并把响应数据转为字符串打印
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while (null != (line = reader.readLine())) {
                        response.append(line);
                    }
                    userdata = response.toString();
                    //回传数据
                    callBackFunc(userdata);
                }
            } catch (Exception e) {
                if (e.toString().contains("timeout")){
                    Toast.makeText(page_daka.this, "请求超时，请检查教务系统是否正常", Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(page_daka.this, e.toString(), Toast.LENGTH_LONG).show();
                }
                e.printStackTrace();
            } finally {
                if (null != connection) {
                    connection.disconnect();
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    CountDownTimer timer = new CountDownTimer(12000, 1000) {
        public void onTick(long millisUntilFinished) {
            btn_daka.setEnabled(false);
            btn_daka.setText("请等待" + millisUntilFinished / 1000 + "秒");
        }

        public void onFinish() {
            //Intent intent = new Intent(MainActivity.this, Main2Activity.class);
            //startActivity(intent);
            btn_daka.setEnabled(true);
            btn_daka.setText("打卡");
        }
    };


    public void callBackFunc(String data){
        //Toast.makeText(MainActivity.this, "Callback:"+data, Toast.LENGTH_SHORT).show();
        //数据写入SP,置”登陆状态“为1
        data=data.toString();
        if (data.contains("打卡成功")){
            String diy_ad =editText_ad.getText().toString();
            rwSPdata("w","diy_ad", diy_ad);
            Toast.makeText(page_daka.this, "打卡成功", Toast.LENGTH_LONG).show();
        }else if(data.contains("已经完成")){
            String diy_ad =editText_ad.getText().toString();
            rwSPdata("w","diy_ad", diy_ad);
            Toast.makeText(page_daka.this, "您今天已经完成了打卡,无需重复打卡", Toast.LENGTH_LONG).show();
        }else if (data.contains("请手动完成打卡")){
            Toast.makeText(page_daka.this, "打卡失败，未知错误，请手动完成打卡", Toast.LENGTH_LONG).show();
        }else if (data.contains("已经加入自动打卡计划")){
            Toast.makeText(page_daka.this, "成功加入自动打卡计划", Toast.LENGTH_LONG).show();
        }else if (data.contains("如需修改邮箱密码")){
            Toast.makeText(page_daka.this, "您已经加入自动打卡计划", Toast.LENGTH_LONG).show();
        }else if (data.contains("账户验证成功")){
            Toast.makeText(page_daka.this, "成功加入自动打卡计划", Toast.LENGTH_LONG).show();
        }else if (data.contains("账户验证失败")){
            Toast.makeText(page_daka.this, "未能自动打卡计划，账户验证失败", Toast.LENGTH_LONG).show();
        }else if (data.contains("删除账号成功")){
            Toast.makeText(page_daka.this, "已经退出自动打卡计划", Toast.LENGTH_LONG).show();
        }else if (data.contains("删除账号失败")){
            Toast.makeText(page_daka.this, "未知错误，删除账号失败，请联系yx@iou.ink检查问题", Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(page_daka.this, data, Toast.LENGTH_LONG).show();
        }

    }


    public String rwSPdata(String flag,String key,String value){
        //email,passwd,vrcode
        SharedPreferences testSP= getSharedPreferences("testSP", Activity.MODE_PRIVATE);
        switch (flag){
            case "w":
                SharedPreferences.Editor editor = testSP.edit();
                editor.putString( key, value );
                editor.apply();
                return "";
            case "r":
                return testSP.getString( key, value );
            default:
                return "";
        }
    }


}